import logging
from flask import jsonify
from flask_login import current_user
from flask_restful import Resource, marshal_with,reqparse
from controllers.errors.character_errors import HTTPCharacterNotExistError
from controllers.errors.emoji_errors import HTTPEmojiPackNotExistError
from controllers.errors.error import HTTPNotLoginError
from controllers.errors.robots_error import HTTPRobotActivateError, HTTPRobotNotFoundError, HTTPRobotNotReadyActiveError
from controllers.errors.timbre_errors import HTTPTimbreNotExistError
from libs.login import login_required
from models.account import Account
from werkzeug.exceptions import InternalServerError
from controllers.mini_app import api
from services.errors.character import CharacterNotExistError
from services.errors.emoji import EmojiPackageNotExistError
from services.errors.robots import RobotActiveNotifyError, RobotAlreadyActivatedError, RobotAreadyActiveByOthersError, RobotConfigIncompleteError, RobotNotExistError, RobotNotReadyError
from services.errors.timbre import TimbreNotExistError
from services.robot.robot_remote_service import RobotRemoteService
from services.robot.robots_service import RobotsService
from fields.robot.robots_fields_def import rob_account_extra_plus_info_fields
from flask_babel import _

class RobotsListApi(Resource):
    @login_required
    @marshal_with(rob_account_extra_plus_info_fields)
    def get(self):
        account = current_user
        if not isinstance(account,Account):
            raise HTTPNotLoginError()
        robot_extra_infos = RobotsService.get_my_robots(account.id)
        return robot_extra_infos
        # return {'result': 'success', 'data': account.to_dict()}, 200

class RobotActiveApi(Resource): 
    @login_required
    def get(self,robot_id:str):
        ret= RobotRemoteService.is_ready_to_active(robot_id)
        ready = False
        if ret:
            ready,_,_,_,_ = ret
        if ready:
            return {"data":True},200
        return  {"data":False},200
    
    @login_required
    def post(self,robot_id:str):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('area_code', type=str, required=False,default=None,location='json')
            parser.add_argument('nick_name', type=str, required=False,default=None,location='json')
            args = parser.parse_args()
            area_code = args.get('area_code',None)
            nick_name = args.get('nick_name',None)
            if not isinstance(current_user,Account):
                raise HTTPNotLoginError()
 
            result = RobotsService.active_robot(robot_id,current_user,area_code,nick_name)
            return result
        except RobotActiveNotifyError:
            raise HTTPRobotActivateError(_("Send Robot active notify failed,please try again later."))
        except RobotNotExistError as e:
            raise HTTPRobotNotFoundError(e.robot_id)
        except RobotConfigIncompleteError as e:
            raise HTTPRobotActivateError(e.description)
        except RobotAreadyActiveByOthersError:
            raise HTTPRobotActivateError(_("The robot already activated."))
        except RobotAlreadyActivatedError:
            raise HTTPRobotActivateError(_("The robot already activated."))
        except RobotNotReadyError:
            raise HTTPRobotNotReadyActiveError()
        except EmojiPackageNotExistError as e:
            raise HTTPEmojiPackNotExistError(e.emoji_pack_id)
        except TimbreNotExistError as e:
            raise HTTPTimbreNotExistError(timbre_id=e.timbre_id)
        except CharacterNotExistError as e:
            raise HTTPCharacterNotExistError(e.character_id) 
        except Exception as e:
            logging.error(e,stack_info=True)
            raise HTTPRobotActivateError(str(e)) 

class RobotBindApi(Resource):
    @login_required
    def get(self,robot_id:str):
        account = current_user
        if not isinstance(account,Account):
            raise HTTPNotLoginError()
        ret= RobotsService.bind_status(robot_id,account.id)
        return  {"data":ret},200

class RobotCurrentConfigApi(Resource):
    @login_required
    def get(self,robot_id:str):
        try:
            return RobotsService.current_config(robot_id)
        except CharacterNotExistError as e:
            raise HTTPCharacterNotExistError(e.character_id)
        except EmojiPackageNotExistError as e:
            raise HTTPEmojiPackNotExistError(e.emoji_pack_id)
        except TimbreNotExistError as e:
            raise HTTPTimbreNotExistError(e.timbre_id)
        except RobotNotExistError as e:
            raise HTTPRobotNotFoundError(e.robot_id)
        except Exception as e:
            raise InternalServerError(str(e))
        
api.add_resource(RobotCurrentConfigApi, '/robots/current_config/<string:robot_id>')
api.add_resource(RobotActiveApi, '/robots/active/<string:robot_id>')
api.add_resource(RobotsListApi, '/robots/list')
api.add_resource(RobotBindApi, '/robots/bind/<string:robot_id>')